using Youz.Common.Helper;
using Youz.Common.DAL;
using Youz.Common.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Youz.Common.BLL
{
    /// <summary>
    /// Right_Menu BLL Class
    /// </summary>
    public partial class Right_MenuBLL : BaseBLL
    {
        public const string CacheKey_Right_Menu_All = "Right_Menu_All";
        public const string CacheKey_Right_Menu_All_HTML = "Right_Menu_All_HTML";
        private Right_MenuDAL dal = new Right_MenuDAL();
        private Lang_LanguageBLL languageBLL = new Lang_LanguageBLL();
        public Right_MenuBLL()
        {
            base.MenuName = "安全管理";
            base.ModuleName = "菜單管理";
        }

        /// <summary>
        ///  新增一条数据
        /// </summary>
        public bool Add(Right_Menu model)
        {
            bool result = dal.Add(model);

            if (result)
            {
                Lang_Language lan = new Lang_Language();
                lan.ModuleName = Convert.ToString(LanguageModule.Right_MenuData);
                lan.LanguageKey = model.MenuID.ToString();
                lan.LanguageValue = model.MenuName;
                lan.WebSite = model.Type == SiteType.Manage ? (int)Utility.CurrentSiteType : (int)SiteType.Web;

                new Lang_LanguageBLL().AddBatch(lan);

                RemoveCacheForGets(model.Type);
            }

            base.WriteOperationLog(OperationType.Add, result, model.MenuID.ToString());

            return result;
        }

        public int BuildMenuID(int parentID)
        {
            int id = GetMaxChild(parentID);

            if (id == 0 && parentID > 0)
            {
                id = 1 * (parentID * 100);
            }

            id = id + 1;

            return id;
        }

        /// <summary>
        /// 删除一条数据
        ///</summary>
        public bool Delete(Int32 MenuID)
        {
            Right_Menu model = Get(MenuID);
            bool result = dal.Delete(MenuID);

            if (result)
            {
                languageBLL.Delete(Enum.GetName(typeof(LanguageModule), LanguageModule.Right_MenuData), MenuID.ToString());

                RemoveCacheForGets(model.Type);
            }

            base.WriteOperationLog(OperationType.Delete, result, MenuID.ToString());

            return result;
        }

        /// <summary>
        /// 是否存在子项
        /// </summary>
        /// <param name="MenuID"></param>
        /// <returns></returns>
        public bool ExistsChild(SiteType type, Int32 MenuID)
        {
            return Gets(type).Exists(m => m.MenuParentID == MenuID);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Right_Menu Get(Int32 MenuID)
        {
            return dal.Get(MenuID);
        }

        /// <summary>
        /// 获取菜单的子项列表
        /// </summary>
        /// <param name="MenuID"></param>
        /// <returns></returns>
        public List<Right_Menu> GetChilds(SiteType type, int MenuID)
        {
            List<Right_Menu> list = Gets(type);
            if (list != null && list.Count > 0)
            {
                list = list.Where(m => m.MenuParentID == MenuID).ToList();
            }
            return list;
        }

        /// <summary>
        /// 得到一个JSON对象
        /// </summary>
        public string GetJson(Int32 MenuID)
        {
            return Utility.GetJsonByObject(Get(MenuID));
        }

        /// <summary>
        /// 获取子菜单的最大ID
        /// </summary>
        /// <param name="MenuID"></param>
        /// <returns></returns>
        public int GetMaxChild(int MenuID)
        {
            return dal.GetMaxChild(MenuID);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet Gets(SiteType type, string sqlWhere)
        {
            DataSet ds = dal.Gets(type, sqlWhere);
            return ds == null ? new DataSet() : ds;
        }

        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        public List<Right_Menu> Gets(SiteType type, bool? isEnabled = null)
        {
            var list = CacheHelper.GetCache(string.Format("{0}_{1}", CacheKey_Right_Menu_All, type)) as List<Right_Menu>;

            if (list == null)
            {
                list = new EntityHelper<Right_Menu>().FillEntity(this.Gets(type, isEnabled.HasValue ? "IsEnabled=" + (isEnabled.GetValueOrDefault() ? "1" : "0") : ""));
                if (list != null)
                {
                    list = list.OrderBy(m => m.Sort).ToList();
                    CacheHelper.SetCache(string.Format("{0}_{1}", CacheKey_Right_Menu_All, type), list);
                }
            }

            return list;
        }

        /// <summary>
        /// 获取后台的所有菜单的HTML
        /// </summary>
        /// <returns></returns>
        public string GetsHTML()
        {
            SiteType type = (SiteType)(int)Utility.CurrentSiteType;
            StringBuilder sb = new StringBuilder();
            List<Right_Menu> list = Gets(type, true);
            IEnumerable<Right_Menu> selectList;

            if (list == null || list.Count == 0)
            {
                return sb.ToString();
            }

            Guid roleID = Utility.CurrentRoleID;

            foreach (Right_Menu menu in list.Where(m => m.MenuParentID == 0))
            {
                if (!Right_RoleRightBLL.Auth(roleID, menu.MenuID))
                {
                    continue;
                }

                selectList = list.Where(m => m.MenuParentID == menu.MenuID);

                sb.AppendFormat("<li><a href=\"{0}\"><i class=\"{1}\"></i><span class=\"text\"> {2}</span>{3}</a>", menu.MenuURL, menu.MenuImage, Lang_LanguageBLL.LanguageByManage(LanguageModule.Right_MenuData, menu.MenuID.ToString(), menu.MenuName), selectList.Count() > 0 ? " <span class=\"indicator\"></span>" : "");

                if (selectList.Count() > 0)
                {
                    sb.Append("<ul>");
                    foreach (Right_Menu child in selectList)
                    {
                        if (!Right_RoleRightBLL.Auth(roleID, child.MenuID))
                        {
                            continue;
                        }

                        sb.AppendFormat("<li><a href=\"{0}\"><i class=\"{1}\"></i><span class=\"text\"> {2}</span></a></li>", child.MenuURL, child.MenuImage, Lang_LanguageBLL.LanguageByManage(LanguageModule.Right_MenuData, child.MenuID.ToString(), child.MenuName));
                    }
                    sb.Append("</ul>");
                }
                sb.Append("</li>");
            }

            return sb.ToString();
        }

        public void RemoveCacheForGets(SiteType type)
        {
            CacheHelper.RemoveCache(string.Format("{0}_{1}", CacheKey_Right_Menu_All, type));
            CacheHelper.RemoveCache(string.Format("{0}_{1}", CacheKey_Right_Menu_All_HTML, type));
        }

        /// <summary>
        ///  保存一条数据
        /// </summary>
        public bool Update(Right_Menu model, Int32 menuID)
        {
            bool result = dal.Update(model, menuID);

            if (result)
            {
                RemoveCacheForGets(model.Type);
            }

            base.WriteOperationLog(OperationType.Update, result, model.MenuID.ToString());

            return result;
        }

        /// <summary>
        /// 获取前台的所有菜单的HTML
        /// </summary>
        /// <returns></returns>
        private string GetsHTMLByWebsite(List<Right_Menu> list)
        {
            StringBuilder sb = new StringBuilder();

            if (list == null || list.Count == 0)
            {
                return sb.ToString();
            }

            Guid roleID = Utility.CurrentRoleID;

            foreach (Right_Menu menu in list.Where(m => m.MenuParentID == 0))
            {
                sb.AppendFormat("<div><span>{0}</span>", Lang_LanguageBLL.LanguageByWebSite(LanguageModule.Right_MenuData, menu.MenuID.ToString(), menu.MenuName));
                sb.Append("<ul>");
                foreach (Right_Menu child in list.Where(m => m.MenuParentID == menu.MenuID))
                {
                    sb.AppendFormat("<li{2}><a href=\"{1}\">{0}</a></li>"
                        , Lang_LanguageBLL.LanguageByWebSite(LanguageModule.Right_MenuData, child.MenuID.ToString(), child.MenuName)
                        , child.MenuURL
                        , WebHelper.CurrentRawUrl.ToLower().Contains(child.MenuURL.ToLower()) ? " class=\"current\"" : "");
                }
                sb.Append("</ul>");
                sb.Append("</div>");
            }

            return sb.ToString();
        }
    }
}